<template>
    <view class="wrap">
        <view class="search">
            <uni-search-bar 
                v-model="state.searchValue" 
                @cancel="cancelSearch" 
                @focus="state.searchFocus = true"
                @input="searchFood"
                @clear="state.isSearch = false;state.searchList = []"
                placeholder="请搜索食物名称"></uni-search-bar>
        </view>
        <!-- 搜索内容 -->
        <view v-if="state.searchFocus" class="search_content">
            <view v-if="state.searchHistory.length > 0 && !state.isSearch" class="search_history">
                <view class="history_top">
                    <view class="title">搜索记录</view>
                    <icon type="" @tap="clearSearchHistory" class="iconfont icon-shanchu1 img_del"></icon>
                </view>
                <view class="history_content">
                    <view class="history_item" v-for="(item, index) in state.searchHistory" :key="index" @tap="historySelect(item)">
                        {{ item }}
                    </view>
                </view>
            </view>
            <view v-if="state.searchList.length === 0 && state.isSearch" class="nodata">
                <image class="img_nodata" src="@/static/image/raozg/noSearchData.png" />
                <view class="nodata_text">暂无数据，换个搜索条件试试?</view>
            </view>
            <view class="search_list">
                <view
                class="search_item"
                v-for="(item, index) in state.searchList"
                :key="index"
                >
                    <view class="name">{{ item.dietName }}</view>
                    <view class="power">{{ item.energy }}千卡/100克</view>
                    <image v-if="item.checked" class="img_right" src="@/static/image/raozg/selected.png" />
                    <image v-if="!item.checked" class="img_right" @tap="foodAdd(item, 'search')" src="@/static/image/raozg/add.png" />
                    <!-- <icon type="" v-if="item.checked" class="iconfont icon-xuanzhong-1 img_right"></icon>
                    <icon type="" v-if="!item.checked" @tap="foodAdd(item, 'search')" class="iconfont icon-zengjia1 img_right"></icon> -->
                </view>
            </view>
        </view>
        <!-- 食物列表 -->
        <view v-if="!state.searchFocus" class="content">
            <view class="left">
                <view
                    :class="['item', state.active == index ? 'on' : '']"
                    v-for="(item, index) in state.typeList"
                    :key="index"
                    @tap="typeSelect(index)"
                >
                    <view v-if="state.active == index" class="line"></view>
                    {{ item.name }}
                </view>
            </view>
            <scroll-view :scroll-top="scrollTop" @scroll="scrollTo" class="scroll-Y" scroll-y="true">
                <view class="right">
                    <view
                    class="item"
                    v-for="(item, index) in state.detailList"
                    :key="index"
                    >
                        <view class="name">{{ item.dietName }}</view>
                        <view class="power">{{ item.energy }}千卡/100克</view>
                        <image v-if="item.checked" class="img_right" src="@/static/image/raozg/selected.png" />
                        <image v-if="!item.checked" class="img_right" @tap="foodAdd(item, 'list')" src="@/static/image/raozg/add.png" />
                        <!-- <icon type="" v-if="item.checked" class="iconfont icon-xuanzhong-1 img_right"></icon>
                        <icon type="" v-if="!item.checked" @tap="foodAdd(item, 'list')" class="iconfont icon-zengjia-1 img_right"></icon> -->
                    </view>
                </view>
            </scroll-view>
        </view>
        <!-- 食物重量设置 -->
        <up-popup :show="state.setShow" :round="32" mode="bottom" closeable @close="close" >
            <view class="food_info">
                <view class="title">
                    {{ formatDate(state.date, 'MM月dd日') + ' ' + state.type }}
                </view>
                <view class="info_top">
                    <view class="name">{{ state.addFood.dietName }}</view>
                    <view class="power">{{ state.addFood.energy }}千卡/100克</view>
                </view>
                <view class="info_detail">
                    <view class="detail_item">
                        <view class="text">热量</view>
                        <view>{{ (state.addFood.energy * (state.addFood.amount / 100)).toFixed(1) }}千卡</view>
                    </view>
                    <view class="detail_item">
                        <view class="text">碳水化合物</view>
                        <view>{{ (state.addFood.cho * (state.addFood.amount / 100)).toFixed(1) }}克</view>
                    </view>
                    <view class="detail_item">
                        <view class="text">蛋白质</view>
                        <view>{{ (state.addFood.pro * (state.addFood.amount / 100)).toFixed(1) }}克</view>
                    </view>
                    <view class="detail_item">
                        <view class="text">脂肪</view>
                        <view>{{ (state.addFood.fat * (state.addFood.amount / 100)).toFixed(1) }}克</view>
                    </view>
                </view>
                <view class="input_info">
                    <input type="digit" class="weight_input" :focus="state.tipFocus" :maxlength="4" @input="onInput" :adjustPosition="false" @keyboardheightchange="onKey" v-model="state.addFood.amount" />
                    <view class="unit">克</view>
                    <view class="hot">(热量约{{ (state.addFood.energy * (state.addFood.amount / 100)).toFixed(1) }}千卡)</view>
                </view>
                <button class="submit" @tap="foodSelect">确定</button>
                <view class="bottom_box" :style="{height: `${ state.bottomHeight }rpx`}"></view>
            </view>
        </up-popup>
        <!-- 固定底部 -->
        <view v-if="!state.setShow && !state.searchFocus" class="fixed">
            <view @tap="state.mealShow = !state.mealShow" class="fixed_left">
                <uni-badge :text="state.selected.length" absolute="rightTop" :offset="[2,8]" size="small" :custom-style="{ background: '#F53F3F', fontSize: '24rpx' }">
                    <icon type="" class="iconfont icon-shiwu1 img_type"></icon>
                </uni-badge>
                <text class="text">{{ state.type }}</text>
                <text type="" v-if="!state.mealShow" class="iconfont icon-jiantou img_arrow img_up"></text>
                <text type="" v-if="state.mealShow" class="iconfont icon-jiantou img_arrow"></text>
            </view>
            <button v-if="state.selected.length > 0" @tap="finish" class="fixed_btn">保存</button>
            <button v-if="state.selected.length == 0" class="fixed_btn disabled">保存</button>
        </view>
        <!-- 已选食物弹窗 -->
        <up-popup :show="state.mealShow" :round="32" mode="bottom" :customStyle="{bottom: '112rpx'}" @close="state.mealShow = false" >
            <view class="total">
                共{{ state.selected.length }}条记录，总计{{ totalPower.toFixed(2) }}千卡
            </view>
            <view v-if="state.selected.length > 0" class="lists">
                <view v-for="(item, index) in state.selected" :key="index" class="item">
                    <view class="name">{{ item.dietName }}</view>
                    <view class="power">{{ item.energy * item.amount / 100 }}千卡/{{ item.amount }}克</view>
                    <icon type="" @tap="deleteFood(item, index)" class="iconfont icon-shanchu1 img_del"></icon>
                </view>
            </view>
        </up-popup>
    </view>
</template>
<script setup lang="ts">
import { reactive, ref, computed, nextTick } from 'vue'
import { query_all_food, query_get_food, save_food, search_food } from '@/api/food'
import { onLoad, onShow } from '@dcloudio/uni-app';
import { debounce, throttle } from '@/utils/tools'
import { formatDate } from '@/utils/util'

const state = reactive({
    userInfo: {},
    searchFocus: false,
    isSearch: false,
    searchValue: '',
    searchHistory: [],
    searchList: [],
    typeList: [],
    detailList: [],
    active: 0,
    type: '',
    date: '',
    selected: [],
    addFood: {},
    addType: '',
    mealShow: false,
    setShow: false,
    tipFocus: false,
    bottomHeight: 0
})
const scrollTop = ref(0)
const oldScrollTop = ref(0)

const totalPower = computed(() => {
    let sum = 0
    if (state.selected.length > 0) {
        state.selected.forEach(item => {
            sum += (item.energy * item.amount) / 100
        })
    }
    return sum
})

onLoad((option) => {
    state.type = option.food ? option.food : ''
    state.date = option.date ? option.date : ''
})
onShow(() => {
    state.userInfo = uni.getStorageSync('userInfo') ? JSON.parse(uni.getStorageSync('userInfo')).patientInfo : {}
    state.searchHistory = uni.getStorageSync('searchHistory') ? JSON.parse(uni.getStorageSync('searchHistory')) : []
    getFoodDict()
})

const getFoodDict = () => {
    query_all_food().then(res => {
        state.typeList = res.data
        state.typeList.forEach(i => {
            i.list.forEach(j => {
                j.checked = false
            })
        })
        state.detailList = state.typeList[state.active].list
        getData()
    })
}
const getData = () => {
  let params = {
    empi: state.userInfo.empi,
    date: state.date
  }
  query_get_food(params).then(res => {
    // 赋值已选中的列表
    res.data.forEach(item => {
        if (state.type == item.dietType) {
            state.selected = item.list
        }
    })
    state.detailList.forEach(item => {
        // 如果已选中的列表没有为false, 有就为true
        item.checked = false
        state.selected.forEach(i => {
            if (i.dietCode == item.dietCode) {
                item.checked = true
            }
        })
    })
  })
}
const cancelSearch = () => {
    state.searchFocus = false
    state.isSearch = false
    state.searchList = []
}
const clearSearchHistory = () => {
    state.searchHistory = []
    uni.removeStorageSync('searchHistory')
}
const searchFood = debounce((e) => {
    if (e == '') {
        state.isSearch = false
        state.searchList = []
        return
    }
    state.isSearch = true
    search_food(state.searchValue).then(res => {
        state.searchList = res.data
        state.searchList.forEach(item => {
            // 如果已选中的列表没有为false, 有就为true
            item.checked = false
            state.selected.forEach(i => {
                if (i.dietCode == item.dietCode) {
                    item.checked = true
                }
            })
        })
        // 保存搜索历史记录
        if (state.searchHistory.indexOf(e) == -1) {
            if (state.searchHistory.length >= 10) {
                state.searchHistory.pop()
            }
            state.searchHistory.unshift(e)
        }
        uni.setStorageSync('searchHistory', JSON.stringify(state.searchHistory))
    })
}, 1000)
const historySelect = (val) => {
    state.searchValue = val
    searchFood(state.searchValue)
}

const typeSelect = (index) => {
    state.active = index
    state.detailList = state.typeList[state.active].list
    state.detailList.forEach(item => {
        state.selected.forEach(i => {
            if (i.dietCode == item.dietCode) {
                item.checked = true
            }
        })
    })
    // 解决view层不同步问题，返回顶部
    scrollTop.value = oldScrollTop.value
    nextTick(() => {
        scrollTop.value = 0
    })
}
const scrollTo = (e) => {
    oldScrollTop.value = e.detail.scrollTop
}
const foodAdd = (item: any, type: string) => {
    state.addType = type
    item.amount = 100
    state.addFood = item
    state.setShow = true
    setTimeout(() => {
        // 解决弹窗打开时，input无法获取焦点问题
        state.tipFocus = true
    },100)
}
const foodSelect = throttle(() => {
    if (!state.addFood.amount || state.addFood.amount == '0') {
        uni.showToast({
            title: '重量不能为0或空!',
            icon: 'error'
        })
        return
    }
    state.detailList.forEach(item => {
        if (item.dietCode == state.addFood.dietCode) {
            item.checked = true
        }
    })
    if (state.addType === 'search') {
        state.searchList.forEach(item => {
            if (item.dietCode == state.addFood.dietCode) {
                item.checked = true
            }
        })
    }
    state.selected.push(state.addFood)
    state.setShow = false
    state.tipFocus = false
}, 300)
const onKey = (e) => {
  const sys = uni.getSystemInfoSync()
  // 自定义弹出键盘事件
  if (e.detail.height) {
    state.bottomHeight = e.detail.height * 2 - (sys.safeAreaInsets.bottom * 2) - 36
  } else {
    state.bottomHeight = 0
  }
}
const onInput = (e) => {
    if (e.detail.value * 1 > 3000) {
        state.addFood.amount = 3000
    }
}

const close = () => {
  state.setShow = false
  state.tipFocus = false
  state.bottomHeight = 0
}
const deleteFood = (item, index) => {
    state.selected.splice(index, 1)
    state.typeList.forEach(i => {
        i.list.forEach(j => {
            if (j.dietCode === item.dietCode) {
                j.checked = false
            }
        })
    })
}
const finish = () => {
    state.selected.forEach(item => {
        item.empi = state.userInfo.empi
        item.dietDate = state.date
        item.dietType = state.type
    })
    save_food(state.selected).then(res => {
        uni.navigateBack({
            delta: 1
        })
    })
}

</script>

<style lang="scss" scoped>
.wrap {
    .search {
        background: #fff;
    }
    .search_content {
        padding: 20rpx 0;
        height: calc(100vh - 152rpx);
        background: #fff;
        .search_history {
            margin: 0 32rpx;
            .history_top {
                display: flex;
                justify-content: space-between;
                margin-bottom: 20rpx;
                .title {
                    font-weight: 500;
                    font-size: 30rpx;
                    color: #333333;
                }
                .img_del {
                    font-size: 40rpx;
                    color: #999;
                }
            }
            .history_content {
                display: flex;
                justify-content: flex-start;
                flex-wrap: wrap;
                gap: 20rpx;
                .history_item {
                    background: #FAFAFA;
                    border-radius: 30rpx;
                    font-weight: 400;
                    font-size: 26rpx;
                    color: #666666;
                    padding: 10rpx 30rpx;
                }
            }
        }
        .nodata {
            text-align: center;
            .img_nodata {
                width: 320rpx;
                height: 240rpx;
                margin-top: 222rpx;
            }
            .nodata_text {
                font-weight: 400;
                font-size: 28rpx;
                color: #666666;
            }
        }
        .search_list {
            height: calc(100vh - 152rpx);
            overflow: auto;
            background: #fff;
            .search_item {
                height: 160rpx;
                padding: 34rpx 32rpx;
                box-sizing: border-box;
                border-bottom: 1rpx solid #e5e6eb;
                position: relative;
                .name {
                    font-weight: 500;
                    font-size: 30rpx;
                    color: #222222;
                    margin-bottom: 10rpx;
                }
                .power {
                    font-weight: 400;
                    font-size: 28rpx;
                    color: #666666;
                }
                .img_right {
                    position: absolute;
                    width: 40rpx;
                    height: 40rpx;
                    right: 32rpx;
                    top: 50%;
                    margin-top: -20rpx;
                }
            }
        }
    }
    .content {
        display: flex;
        border-top: 1rpx solid #e5e6eb;
        height: calc(100vh - 256rpx - env(safe-area-inset-bottom));
        .left {
          width: 244rpx;
          overflow: auto;
          .item {
            background: #fafafa;
            height: 100rpx;
            line-height: 100rpx;
            padding-left: 32rpx;
            border-bottom: 1rpx solid #fff;
            font-size: 32rpx;
            font-weight: 700;
            position: relative;
            &:nth-last-child(1) {
              border-bottom: 0rpx solid #fff;
            }
            &.on {
              background: #fff;
              color: #00d1b6;
            }
            .line {
                width: 12rpx;
                height: 32rpx;
                position: absolute;
                left: 0;
                top: 50%;
                margin-top: -16rpx;
                background: #00D1B6;
                border-radius: 0 4rpx 0 4rpx;
            }
          }
        }
        .scroll-Y {
            height: calc(100vh - 256rpx - env(safe-area-inset-bottom));
        }
        .right {
          flex: 1;
        //   overflow: auto;
          background: #fff;
          .item {
            height: 160rpx;
            padding: 34rpx 32rpx;
            box-sizing: border-box;
            border-bottom: 1rpx solid #e5e6eb;
            position: relative;
            .name {
                font-weight: 500;
                font-size: 30rpx;
                color: #222222;
                margin-bottom: 10rpx;
            }
            .power {
                font-weight: 400;
                font-size: 28rpx;
                color: #666666;
            }
            .img_right {
                position: absolute;
                width: 40rpx;
                height: 40rpx;
                right: 32rpx;
                top: 50%;
                margin-top: -20rpx;
            }
          }
        }
    }
    .fixed {
        position: fixed;
        background: #fff;
        bottom: 0;
        left: 0;
        z-index: 99999;
        width: 100%;
        box-sizing: border-box;
        border-top: 1rpx solid #e5e6eb;
        padding: 12rpx 40rpx;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-bottom: calc(30rpx + constant(safe-area-inset-bottom));
        padding-bottom: calc(30rpx + env(safe-area-inset-bottom));
        .fixed_left {
            display: flex;
            justify-content: flex-start;
            align-items: center;
            .img_type {
                font-size: 48rpx;
                color: #00D1B6;
                transform: translateY(6rpx);
            }
            .text {
                font-weight: 500;
                font-size: 30rpx;
                color: #222222;
                margin: 0 12rpx;
            }
            .img_arrow {
                font-size: 32rpx;
                color: #b8bbbd;
                transform: translateY(2rpx);
            }
            .img_up {
                transform: rotateX(180deg)
            }
        }
        .fixed_btn {
            width: 280rpx;
            height: 88rpx;
            line-height: 88rpx;
            background: #00D1B6;
            border-radius: 44rpx;
            font-weight: 500;
            font-size: 32rpx;
            color: #FFFFFF;
            margin: 0;
        }
        .disabled {
            background: #ccc;
        }
    }
    .u-popup {
        // 设置重量弹窗
        .food_info {
            padding: 0 32rpx;
            .title {
                width: 100%;
                text-align: center;
                height: 104rpx;
                line-height: 104rpx;
                font-weight: 500;
                font-size: 30rpx;
                color: #333333;
            }
            .info_top {
                .name {
                    font-weight: 500;
                    font-size: 30rpx;
                    color: #222222;
                    margin-bottom: 10rpx;
                }
                .power {
                    font-weight: 400;
                    font-size: 28rpx;
                    color: #666666;
                }
            }
            .info_detail {
                display: flex;
                justify-content: space-between;
                margin: 26rpx 0 30rpx;
                padding: 20rpx 0;
                box-sizing: border-box;
                border-top: 1rpx solid #e5e6eb;
                border-bottom: 1rpx solid #e5e6eb;
                font-weight: 400;
                font-size: 24rpx;
                color: #999999;
                .detail_item {
                    flex: 1;
                    text-align: center;
                    .text {
                        margin-bottom: 10rpx;
                    }
                }
            }
            .input_info {
                text-align: center;
                position: relative;
                .weight_input {
                    width: 200rpx;
                    height: 84rpx;
                    border-bottom: 4rpx solid #1cd7ae;
                    margin: 0 auto;
                    font-weight: 500;
                    font-size: 60rpx;
                    color: #1CD7AE;
                }
                .unit {
                    font-weight: 500;
                    font-size: 24rpx;
                    color: #1CD7AE;
                    position: absolute;
                    right:235rpx;
                    top: 0;
                }
                .hot {
                    font-weight: 400;
                    font-size: 24rpx;
                    color: #666666;
                    margin-top: 16rpx;
                }
            }
            .submit {
                width: 100%;
                height: 88rpx;
                line-height: 88rpx !important;
                background: #00D1B6;
                border-radius: 50rpx;
                font-weight: 500;
                font-size: 32rpx !important;
                padding: 0 !important;
                color: #FFFFFF;
                margin: 76rpx 0 32rpx;
            }
        }
        // 查看已选
        .total {
            font-weight: 400;
            font-size: 24rpx;
            color: #666666;
            margin: 34rpx 32rpx 24rpx;
        }
        .lists {
            padding: 0 32rpx 32rpx;
            max-height: 700rpx;
            overflow: auto;
            .item {
                height: 118rpx;
                border-bottom: 1rpx solid #e5e6eb;
                margin: 24rpx 0;
                box-sizing: border-box;
                position: relative;
                .name {
                    font-weight: 500;
                    font-size: 32rpx;
                    color: #222222;
                    margin-bottom: 10rpx;
                }
                .power {
                    font-weight: 400;
                    font-size: 28rpx;
                    color: #666666;
                }
                .img_del {
                    position: absolute;
                    font-size: 40rpx;
                    color: #999;
                    right: 0;
                    top: 50%;
                    margin-top: -20rpx;
                }
                &:first-child {
                    margin-top: 0;
                }
            }
        }
    }
    ::v-deep .uni-searchbar {
        padding: 24rpx 32rpx;
    }
    ::v-deep .uni-searchbar__text-placeholder {
        font-size: 30rpx !important;
        color: #999 !important;
    }
    ::v-deep .uni-searchbar__box {
        justify-content: flex-start;
        border-radius: 40rpx !important;
        background: #fafafa !important;
        height: 80rpx !important;
        padding: 20rpx 24rpx !important;
    }
    ::v-deep .uni-searchbar__box-search-input {
        font-size: 30rpx !important;
    }
    ::v-deep .uni-searchbar__cancel {
        font-weight: 500;
        font-size: 30rpx !important;
        line-height: 80rpx !important;
        color: #00D1B6 !important;
    }
    ::v-deep .u-icon__icon {
        font-size: 32rpx !important;
        line-height: 50rpx !important;
    }
}
</style>
